package com.gdcontrol.desktop.visao.consulta;

import com.gdcontrol.desktop.controle.manutencao.ControleManutencaoGrupoAlimento;
import com.gdcontrol.desktop.controle.consulta.ControleConsultaGrupoAlimento;
import com.gdcontrol.desktop.util.tablemodel.GrupoAlimentoTableModel;
import com.gdcontrol.desktop.visao.manutencao.VisaoManutencaoGrupoAlimento;
import com.gdcontrol.entidade.GrupoAlimento;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author gustavo
 */
public class VisaoConsultaGrupoAlimento extends VisaoConsultaPadrao {
    
    private static final String OPCAO_ID = "ID";
    private static final String OPCAO_DESCRICAO = "Descrição";

    /**
     * Creates new form VisaoConsultaGrupoAlimento
     * @param parent
     * @param modal
     */
    public VisaoConsultaGrupoAlimento(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        carregaGrupoAlimentos();
        getOpcoesPesquisa();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbGrupoAlimento = new javax.swing.JTable();
        btNovo = new javax.swing.JButton();
        btExcluir = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        cbCampoPesquisa = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        edPesquisa = new javax.swing.JTextField();
        btPesquisar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consulta Grupo Alimento");

        tbGrupoAlimento.setModel(tableModelGrupoAlimento);
        tbGrupoAlimento.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbGrupoAlimentoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbGrupoAlimento);

        btNovo.setText("Novo");
        btNovo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btNovoMouseClicked(evt);
            }
        });

        btExcluir.setText("Excluir");
        btExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btExcluirMouseClicked(evt);
            }
        });

        btAlterar.setText("Alterar");
        btAlterar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btAlterarMouseClicked(evt);
            }
        });
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        jLabel1.setText("Campo Pesquisa:");

        jLabel2.setText("Pesquisa:");

        edPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                edPesquisaKeyPressed(evt);
            }
        });

        btPesquisar.setText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btNovo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btAlterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btExcluir))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(cbCampoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(edPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btPesquisar)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbCampoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(edPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btPesquisar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btNovo)
                    .addComponent(btAlterar)
                    .addComponent(btExcluir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tbGrupoAlimentoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbGrupoAlimentoMouseClicked
        if (evt.getClickCount() == 2) {
            btAlterarActionPerformed(null);
        }
    }//GEN-LAST:event_tbGrupoAlimentoMouseClicked

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        if(!edPesquisa.getText().isEmpty()){
            tableModelGrupoAlimento.limpar();
            String pesquisa = (String) cbCampoPesquisa.getSelectedItem();
            switch(pesquisa){
                case OPCAO_ID:
                    try{
                        filtraId(Integer.parseInt(edPesquisa.getText()));
                    }catch(NumberFormatException e){}
                    break;
                case OPCAO_DESCRICAO:
                    filtraDescricao(edPesquisa.getText());
                    break;    
            }
            tableModelGrupoAlimento.fireTableDataChanged();
        }else{
            carregaGrupoAlimentos();
        }
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void edPesquisaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_edPesquisaKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            btPesquisarActionPerformed(null);
        }
    }//GEN-LAST:event_edPesquisaKeyPressed

    private void btNovoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btNovoMouseClicked
        VisaoManutencaoGrupoAlimento visaoManutencao = new VisaoManutencaoGrupoAlimento(null, true);
        visaoManutencao.setVisible(true);
        carregaGrupoAlimentos();
    }//GEN-LAST:event_btNovoMouseClicked

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        int indice = tbGrupoAlimento.getSelectedRow();
        if (indice >= 0) {
            VisaoManutencaoGrupoAlimento manutencao = new VisaoManutencaoGrupoAlimento(null, true);
            ControleManutencaoGrupoAlimento controleManutencao = (ControleManutencaoGrupoAlimento) manutencao.getControle();
            controleManutencao.setModelo(tableModelGrupoAlimento.getGrupoAlimento(indice));
            controleManutencao.setTela(manutencao);
            controleManutencao.carregaTela();
            manutencao.setVisible(true);
            carregaGrupoAlimentos();
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void btAlterarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btAlterarMouseClicked

    }//GEN-LAST:event_btAlterarMouseClicked

    private void btExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btExcluirMouseClicked
        int indice = tbGrupoAlimento.getSelectedRow();
        if (indice >= 0) {
            int opcao = JOptionPane.showConfirmDialog(this, "Confirma exclusão do Grupo de Alimento selecionado?");
            if(opcao == JOptionPane.YES_OPTION){
                getControle().excluir(tableModelGrupoAlimento.getGrupoAlimento(indice));
                carregaGrupoAlimentos();
            }
        }
    }//GEN-LAST:event_btExcluirMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaGrupoAlimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaGrupoAlimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaGrupoAlimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaGrupoAlimento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                VisaoConsultaGrupoAlimento dialog = new VisaoConsultaGrupoAlimento(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JComboBox cbCampoPesquisa;
    private javax.swing.JTextField edPesquisa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbGrupoAlimento;
    // End of variables declaration//GEN-END:variables

    private GrupoAlimentoTableModel tableModelGrupoAlimento = new GrupoAlimentoTableModel();
    private ControleConsultaGrupoAlimento controle = new ControleConsultaGrupoAlimento();

    @Override
    public ControleConsultaGrupoAlimento getControle() {
        return this.controle;
    }

    private void carregaGrupoAlimentos() {
        tableModelGrupoAlimento.limpar();
        for (GrupoAlimento grp : (List<GrupoAlimento>) getControle().listar()) {
            tableModelGrupoAlimento.addGrupoAlimento(grp);
        }
        tableModelGrupoAlimento.fireTableDataChanged();
    }
    
    private void filtraId(int id){
        GrupoAlimento grp = getControle().filtraId(id);
        if(grp != null){
            tableModelGrupoAlimento.addGrupoAlimento(grp);
        }
    }
    
    private void filtraDescricao(String descricao){
        for (GrupoAlimento grp : (List<GrupoAlimento>) getControle().filtraDescricao(descricao)) {
            tableModelGrupoAlimento.addGrupoAlimento(grp);
        }
    }

    @Override
    public void getOpcoesPesquisa() {
        Vector comboBoxItems = new Vector();
        comboBoxItems.add(OPCAO_ID);
        comboBoxItems.add(OPCAO_DESCRICAO);
        final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
        this.cbCampoPesquisa.setModel(model);
    }
}
